// cloudfunctions/updateOrderStatus/index.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const {
            orderId,
            newStatus
        } = event

        if (!orderId || newStatus === undefined) {
            return {
                success: false,
                message: '参数缺失'
            }
        }

        // 开启事务
        const transaction = await db.startTransaction()

        try {
            // 1. 更新订单状态
            const orderRes = await transaction.collection('orders').doc(orderId).get()
            const order = orderRes.data
            console.log(order);
            if (!order) {
                await transaction.rollback()
                return {
                    success: false,
                    message: '订单不存在'
                }
            }
            // 防止重复处理已完成的订单
            if (order.status === 4 && newStatus === 4) {
                await transaction.rollback()
                return {
                    success: false,
                    message: '订单已完成，无需重复处理'
                }
            }
            const updateData = {
                status: newStatus
            }
            if (newStatus === 3) updateData.shipTime = db.serverDate()
            if (newStatus === 4) updateData.receiveTime = db.serverDate()
            if (newStatus === 5) updateData.refundTime = db.serverDate()

            await transaction.collection('orders').doc(orderId).update({
                data: updateData
            })

            // 2. 确认收货时增加积分
            if (newStatus === 4) {
                 // 订单金额转为积分（1元=100积分）
                const points = Math.floor(Number(order.price) * 100) 
                const userId = order.sellerId
                // 生成积分记录
                const record = {
                    recordId: `REC_${Date.now()}`,
                    type: 1,
                    amount: points,
                    orderId: orderId,
                    createTime: db.serverDate(),
                    remark: `订单(${order.outTradeNo})确认收货获得积分（1元=100积分）`
                }
                // 检查用户是否已有积分记录
                const pointsRes = await transaction.collection('user_points')
                    .where({
                        userId: userId
                    })
                    .get()

                // 如果已有积分记录，更新它
                if (pointsRes.data && pointsRes.data.length > 0) {
                    const pointsDocId = pointsRes.data[0]._id
                    const existingPoints = pointsRes.data[0].points
                    const existingTotalPoints = pointsRes.data[0].totalPoints

                    // 确保积分字段是数值类型
                    let updateData = {
                        records: _.unshift(record)
                    }
                    // 如果现有字段是字符串，先转换为数值
                    if (typeof existingPoints === 'string') {
                        updateData.points = parseFloat(existingPoints) + points
                    } else {
                        updateData.points = _.inc(points)
                    }

                    if (typeof existingTotalPoints === 'string') {
                        updateData.totalPoints = parseFloat(existingTotalPoints) + points
                    } else {
                        updateData.totalPoints = _.inc(points)
                    }

                    await transaction.collection('user_points').doc(pointsDocId).update({
                        data: updateData
                    })
                } else {
                    await transaction.collection('user_points').add({
                        data: {
                            userId: userId,
                            points: points,
                            totalPoints: points,
                            records: [record]
                        }
                    })
                }
            }

            // 提交事务
            await transaction.commit()
            return {
                success: true,
                message: '操作成功'
            }

        } catch (error) {
            await transaction.rollback()
            throw error
        }

    } catch (error) {
        console.error('操作失败:', error)
        return {
            success: false,
            message: error.message || '操作失败'
        }
    }
}